package dao

import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import shared.pojo.Pojo.MemberAddData
import slick.jdbc.JdbcProfile

import javax.inject.{Inject, Singleton}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
@Singleton
class UserDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {


  import utils.MyPostgresProfile.api._

  type MyRow = UserRow
  val table = User

  def selectByUserData(user: MemberAddData): Future[Option[UserRow]] = {
    db.run(table.filter(x => x.name === user.account)
      .filter(_.password === user.password).result.headOption)
  }

  def insert(row: MyRow) = {
    db.run(table += row)
  }

  def selectAll: Future[Seq[MyRow]] = db.run(table.sortBy(_.id.desc).result)

  def selectByName(name: String) = db.run(table.
    filter(_.name === name).result.headOption)

  def nameExist(name: String) = db.run(table.
    filter(_.name === name).exists.result)

  def deleteById(id: Int): Future[Unit] = db.run(table.filter(_.id === id).delete).map(_ => ())

  def selectById(id: Int)= db.run(table.
    filter(_.id === id).result.head)

  def selectByNameSome(name: String) = db.run(table.
    filter(_.name === name).result.head)

  def update(row: MyRow): Future[Unit] = db.run(table.filter(_.name === row.name).update(row)).
    map(_ => ())

  def updates(rows: Seq[MyRow]) = {
    val action = DBIO.sequence{
     rows.map{row=>
        table.filter(_.id===row.id).update(row)
      }
    }.transactionally
    db.run(action)
  }

}
